/*
 * @Description: 权限、路由控制
 * @Version: 1.0
 * @Autor: JiaJun Wu
 * @Date: 2021-11-04 18:48:19
 * @LastEditors: jiajun wu
 * @LastEditTime: 2021-12-07 12:05:52
 */
import router from "./router";
import store from './store'
import NProgress from 'nprogress'
import "nprogress/nprogress.css";
import { setDocumentTitle } from './utils/domUtil';
import { getToken } from './utils/util';
import config from '@/config/default/setting.config'

// 白名单列表
const whiteList = ["/user/login", "/user/register"]

/** 跳转统一登录
 *  @param {string} backurl 登录成功后返回的地址
 */
const goToLogin = (backurl: string) => {
  let url: string = config.loginUrl as string
  if (url.indexOf('?') < 0) {
    url = url + '?';
  }
  backurl = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + window.location.pathname + '#' + backurl;
  backurl = encodeURIComponent(backurl);
  window.location.href = url + '&backurl=' + backurl
}


NProgress.configure({ showSpinner: false })

router.beforeEach((to, from, next) => {
  NProgress.start()
  // 中断上一页的请求
  store.dispatch('removeHttpRequestList');
  if (!getToken() && to.path === '/user/login') {
    // next()
    goToLogin("/")
    NProgress.done()
  }
  // token参数处理
  if (to.query.token || from.query.token) {
    store.dispatch('app/setToken', to.query.token || from.query.token);
  }
  if (from.query.isIframe) {
    to.query['isIframe'] = from.query.isIframe
  }

  // 设置标题
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(to))
  if (getToken()) {
    // 如果已认证，并且又请求登录页面，则返回首页
    if (to.path === '/user/login') {
      next({ path: '/' })
      NProgress.done()
      return;
    }

    if (!store.getters['userInfo']) {
      store.dispatch('isAuthed').then(() => {
        next({ path: to.fullPath ? to.fullPath : to.path });
        NProgress.done()
      }).catch(() => {
        // 跳转到登录页面
        goToLogin("/")
        // next('/user/login')
        NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
      })
      return;
    }

    // 直接放行
    next()
    NProgress.done()
  } else {
    if (whiteList.includes(to.path)) {
      next()
      NProgress.done()
    } else {
      store.dispatch("isAuthed").then(() => {
        next({ path: to.fullPath ? to.fullPath : to.path })
      }).catch(() => {
        // next("/user/login")
        goToLogin("/")
        NProgress.done()
      })
    }
  }
})
